package com.xm.bluetoothkotlin.search

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter.LeScanCallback
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ThreadUtils
import com.xm.bluetoothkotlin.BluetoothManager
import com.xm.bluetoothkotlin.device.BluetoothDeviceData

/**
 * @创建者:小垚
 * @时间:2021/11/11
 *@描述: 蓝牙搜索回调
 */
class BluetoothScanCallback : ScanCallback(), LeScanCallback {


    @SuppressLint("MissingPermission")
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        if (result.device.name != null && result.device.name.isNotEmpty()) {
            notifyOnSearchSuccess(result.device, result.device.address, result.device.name, result.rssi)
        }
        super.onScanResult(callbackType, result)
    }


    @SuppressLint("MissingPermission")
    override fun onLeScan(result: BluetoothDevice, rssi: Int, data: ByteArray?) {
        if (result.name != null && result.name.isNotEmpty()) {
            notifyOnSearchSuccess(result, result.address, result.name, rssi)
        }
    }


    override fun onBatchScanResults(results: MutableList<ScanResult>) {
        super.onBatchScanResults(results)
    }

    override fun onScanFailed(errorCode: Int) {
        notifyOnSearchFailed(errorCode)
        super.onScanFailed(errorCode)
    }


    /**
     * 通知搜索到设备
     */

    private fun notifyOnSearchSuccess(device: BluetoothDevice, address: String, name: String, rssi: Int) {
        val filter = BluetoothManager.searchDevices.filter { address == it.address }
        if (filter.isNullOrEmpty()) {
            var name = if (name.isNullOrEmpty()) {
                SPStaticUtils.getString(address, "")
            } else {
                SPStaticUtils.put(address, name)
                name
            }
            val newDevice = BluetoothDeviceData(device, address, name, rssi)
            BluetoothManager.searchDevices.add(newDevice)
            ThreadUtils.runOnUiThread {
                BluetoothManager.searchs.forEachIndexed { _, bluetoothScanCallback ->
                    bluetoothScanCallback.onSearchSuccess(BluetoothManager.searchDevices, newDevice)
                }
            }
        }
    }

    /**
     * 通知搜索失败
     */
    private fun notifyOnSearchFailed(errorCode: Int) {
        ThreadUtils.runOnUiThread {
            BluetoothManager.searchs.forEachIndexed { index, bluetoothScanCallback ->
                bluetoothScanCallback.onSearchFailed(errorCode.toString())
            }
        }
    }

}